-- InventorySlot should be either "mainhand" or "offhand"
-- Returns: Handled, BuffExists
local function SearchPlayerWeaponBuff(Tooltip, BuffName, InventorySlot)
	if InventorySlot ~= "mainhand" and InventorySlot ~= "offhand" then return nil, nil end

	local slotName = nil
	if string.lower(InventorySlot) == "mainhand" then 
		slotName = "MainHandSlot" 
	elseif string.lower(InventorySlot) == "offhand" then 
		slotName = "SecondaryHandSlot" 
	end

	Tooltip:ClearLines()
	Tooltip:SetInventoryItem("player", GetInventorySlotInfo(slotName))
	for i = 1, Tooltip:NumLines() do
		local text = getglobal("TurtleMacrosTipTextLeft" .. i):GetText() or ""
		if string.find(text, BuffName) then
			return 1, 1
		end
	end
	return 1, nil
end

-- Returns: Handled, BuffExist, Buff id
local function SearchTargetBuffnDebuff(Tooltip, BuffName, Unit)
	local i = 1
	while UnitBuff(Unit, i) do 
		Tooltip:ClearLines()
		Tooltip:SetUnitBuff(Unit,i)
		if string.find(TMacros.NameText:GetText() or "", BuffName) then
			return 1, 1, i
		end
		i = i + 1
	end
	
	i = 1
	while UnitDebuff(Unit, i) do 
		Tooltip:ClearLines()
		Tooltip:SetUnitDebuff(Unit,i)
		if string.find(TMacros.NameText:GetText() or "", BuffName) then
			return 1, 1, i
		end;
		i = i + 1
	end

	return nil, nil, nil
end

function TMacros:HasBuff(BuffName, Unit)
    if (not BuffName) then return nil end

    local unit = Unit
    if (not unit) then unit = "player" end

	self.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")

	local handled, hasBuff = SearchPlayerWeaponBuff(self.ToolTip, BuffName, unit)
	if handled then return hasBuff end

	_, hasBuff = SearchTargetBuffnDebuff(self.ToolTip, BuffName, unit)
	return hasBuff
end


function TMacros:NoBuff(BuffName, Unit)
	return not self:HasBuff(BuffName, Unit)
end

function TMacros:GetDebuffStack(DebuffName, Unit)
	local tool, unit, i = self.ToolTip, Unit or "player", 1
	tool:SetOwner(UIParent, "ANCHOR_NONE");

	while true do
		local icon, stack = UnitDebuff(unit, i)
		if not icon then break end
		tool:ClearLines()
		tool:SetUnitDebuff(unit, i)
		local name = TMacros.NameText:GetText() or ""
		if string.find(name, DebuffName) then 
			return stack
		end
		i = i + 1
	end
	return 0
end

function TMacros:CancelBuff(Buffname)
	for i = 0, 32 do
		self.ToolTip:SetOwner(UIParent, "ANCHOR_NONE")
		self.ToolTip:SetPlayerBuff(i)
		local name = TMacros.NameText:GetText()
		if not name then break end
		if strfind(strlower(name), Buffname) then
			CancelPlayerBuff(i)
			break
		end
		self.ToolTip:Hide()
	end
end